package cn.uc.app;


import java.util.ArrayList;

import cn.uc.bs.dip.ImageBlurer;
import cn.uc.bs.dip.ImageFilmer;
import cn.uc.bs.dip.ImageOldMaker;
import cn.uc.bs.dip.ImageProcessor;
import cn.uc.bs.dip.ImageReflection;
import cn.uc.bs.dip.ImageReverser;
import cn.uc.bs.dip.ImageSharper;
import cn.uc.bs.dip.ImageSketcher;
import cn.uc.bs.dip.ImageSunshiner;
import cn.uc.component.TVOffAnimation;
import cn.uc.util.DateUtil;
import cn.uc.util.FileUtil;
import cn.uc.util.ImageUtil;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

public class GalleryActivity extends Activity implements AnimationListener, ViewFactory{   
    public static final int FIRST_NUM = 4;
    
    private Gallery myGallery;
    private ImageSwitcher switcher; 
    private MyImageAdapter adapter;
    private Bitmap mBitmap = null;
    private Bitmap mBitmapBackup = null;
//    private ImageView mImageView = null;
    private Handler mHandler = null;
    private TextView tips = null;
    private boolean isProcessing = false;
    
    private ArrayList<Bitmap> images = new ArrayList<Bitmap>();
    
    private int mLastMotionX, mLastMotionY;  
    //是否移动了  
    private boolean isMoved;  
    private boolean isReleased;  
    //计数器，防止多次点击导致最后一次形成longpress的时间变短  
    private int mCounter; 
    //长按的runnable  
    private Runnable mLongPressRunnable;  
    //移动的阈值  
    private static final int TOUCH_SLOP = 20;
    private static final int SWITCH_DIS = 80;

    
    private Animation mAnimation;
    
    private PopupWindow imageMenu = null;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Gallery");
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏
        requestWindowFeature( Window.FEATURE_INDETERMINATE_PROGRESS); //标题栏进度条
        setContentView(R.layout.gallery);
        
        loadImages();
        
        myGallery = (Gallery)findViewById(R.id.myGallery);
        //这段代码是杨丰盛老师的《android开发揭秘》中这样写的
        //myGallery.setBackgroundResource(R.drawable.bg0);
        adapter = new MyImageAdapter(this);
        //设置背景风格。Gallery背景风格定义在attrs.xml中
        TypedArray typedArray = obtainStyledAttributes(R.styleable.Gallery);
        adapter.setGalleryItemBackground(typedArray.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0));
        myGallery.setAdapter(adapter);
        myGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long arg3) {
                // XXX Auto-generated method stub
                if(!isProcessing){
                    mBitmap = images.get(pos);
                    mBitmapBackup = mBitmap;
 //                   mImageView.setImageBitmap(mBitmap);
                    BitmapDrawable sDrawable= new BitmapDrawable(mBitmap);
                    switcher.setImageDrawable(sDrawable);
                }
            }

            public void onNothingSelected(AdapterView<?> arg0) {
                // XXX Auto-generated method stub
                
            }
        });
        
      //设置ImageSwitcher控件   
        switcher = (ImageSwitcher) findViewById(R.id.gallery_switcher);   
        switcher.setFactory(this);   
        switcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));   
        switcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));   
        switcher.setOnTouchListener(new OnTouchListener(){   
            /*  
             * 在ImageSwitcher控件上滑动可以切换图片  
             */  
            public boolean onTouch(View v, MotionEvent event) { 
              int x = (int)event.getX();//取得按下时的坐标   
              int y = (int)event.getY();
              switch(event.getAction()) {  
              case MotionEvent.ACTION_DOWN:  
                  mLastMotionX = x;//取得按下时的坐标   
                  mLastMotionY = y;
                  
                  mCounter++;  
                  isReleased = false;  
                  isMoved = false;  
                  new Handler().postDelayed(mLongPressRunnable, ViewConfiguration.getLongPressTimeout());  
                  break;  
                  
              case MotionEvent.ACTION_MOVE:  
                  if(isMoved) break;  
                  if(Math.abs(mLastMotionX - x) > TOUCH_SLOP || Math.abs(mLastMotionY - y) > TOUCH_SLOP) {  
                      //移动超过阈值，则表示移动了  
                      isMoved = true;  
                  }  
                  break;  
                  
              case MotionEvent.ACTION_UP:  
                  //释放了  
                  isReleased = true;  
                  
                  int index=0;   
                  if(x - mLastMotionX > SWITCH_DIS){//从左拖到右，即看前一张   
                      //如果是第一，则去到尾部   
                      if(myGallery.getSelectedItemPosition()==0)   
                          index=myGallery.getCount()-1;   
                      else  
                          index=myGallery.getSelectedItemPosition()-1;   
                  }else if(mLastMotionX - x > SWITCH_DIS){//从右拖到左，即看后一张   
                      //如果是最后，则去到第一   
                      if(myGallery.getSelectedItemPosition()==(myGallery.getCount()-1))   
                          index=0;   
                      else  
                          index=myGallery.getSelectedItemPosition()+1;   
                  }   
                  //改变gallery图片所选，自动触发ImageSwitcher的setOnItemSelectedListener   
                  myGallery.setSelection(index, true);   
                  break;  
              }  
              
              return true;               
            }
        });          
        
        LinearLayout layout = new LinearLayout(this);
        Button btnSave = new Button(this);
        btnSave.setText("Save");
        btnSave.setOnClickListener(new OnClickListener() {            
            public void onClick(View v) {
                // XXX Auto-generated method stub
                imageMenu.dismiss();
                saveImage();
            }
        });
        layout.addView(btnSave);
        imageMenu = new PopupWindow(layout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        imageMenu.setAnimationStyle(android.R.style.Animation_Toast);    
        imageMenu.setFocusable(true);
        // 以下两行加上去后就可以使用BACK键关闭POPWINDOW
 //       ColorDrawable dw = new ColorDrawable(0xb0000000);
        imageMenu.setBackgroundDrawable(new BitmapDrawable());

//        mImageView = (ImageView)findViewById(R.id.gallery_image_view);
//        if(images.isEmpty()){
//            mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);// ImageUtil.zoomBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.image), 320, 240);
//        }else{
//            mBitmap = images.get(0);
//        }
//        
//        mBitmapBackup = mBitmap;
//       
//        mImageView.setImageBitmap(mBitmap);
//        // 设置ImageView的伸缩规格，用了自带的属性值
//        mImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
//        // 设置布局参数
////        mImageView.setLayoutParams(new Gallery.LayoutParams(160, 120));
//        
        
        tips = (TextView)findViewById(R.id.gallery_text_view);
        tips.setText("");
        
        mHandler = new Handler(){
            public void handleMessage(Message msg){
                switch(msg.what){
                case Values.MSG_IMAGE_PROCESSED:
                    mBitmap = (Bitmap)msg.obj;
 //                   mImageView.setImageBitmap(mBitmap);
                    BitmapDrawable sDrawable= new BitmapDrawable(mBitmap);
                    switcher.setImageDrawable(sDrawable);
                    tips.setText("");
                    isProcessing = false;
                    setProgressBarIndeterminateVisibility(false);
                    break;
                }

                super.handleMessage(msg);
            }
        };
        
        
        mLongPressRunnable = new Runnable() {             
            public void run() {  
                mCounter--;  
                //计数器大于0，说明当前执行的Runnable不是最后一次down产生的。  
                if(mCounter>0 || isReleased || isMoved) return; 
//                Toast.makeText(GalleryActivity.this, "Image is saving", 3000).show();
                imageMenu.showAtLocation(switcher, Gravity.CENTER, mLastMotionX - switcher.getLeft(), mLastMotionY - switcher.getBottom());
            }  
        }; 
        
        mAnimation = AnimationUtils.loadAnimation(this, R.anim.myanim);
        mAnimation.setAnimationListener(this);
    }
    
    private void loadImages(){
        final ArrayList<String> imagePaths = FileUtil.getAllImageFiles(Values.STORE_ROOT);//DiaryManager.getAllImages();
        int size = Math.min(FIRST_NUM, imagePaths.size());
        for(int i = 0; i < size; i++){
            images.add(/*DiaryManager.getBitmapFromSDCard*/ImageUtil.readBitMap(imagePaths.get(i)));
        }
        
        if(imagePaths.size() > size){
            new Handler().postDelayed(new Runnable() {                
                public void run() {
                    // XXX Auto-generated method stub
                    for(int i = FIRST_NUM; i < imagePaths.size(); i++){
                        images.add(/*DiaryManager.getBitmapFromSDCard*/ImageUtil.readBitMap(imagePaths.get(i)));
                    }
                    adapter.notifyDataSetChanged();//刷新Adapter
                    myGallery.invalidate();
                }
            }, 1000);
        }
    }
    
    private void save(){
        //save image
        ImageUtil.saveBitmap(mBitmap, Values.STORE_ROOT, DateUtil.getCurrentTimString() + ".png", Bitmap.CompressFormat.PNG);
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
//        menu.add("Film");
//        menu.add("Old Remember");
//        menu.add("Sunshine");
//        menu.add("Sharper");
//        menu.add("Blur");
//        menu.add("Shadow");
//        menu.add("Sketch");
//        menu.add("Revese");
//
//        return super.onCreateOptionsMenu(menu);
        
        //method2
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.options_menu, menu);
      return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        ImageProcessor sProessor = null;
        switch (item.getItemId()) {
        case R.id.menu_gallery_film:
            sProessor = new ImageFilmer(mBitmapBackup);
            break;
        case R.id.menu_gallery_rememble:
            sProessor = new ImageOldMaker(mBitmapBackup);
            break;
        case R.id.menu_gallery_sunshine:
            sProessor = new ImageSunshiner(mBitmapBackup);
            break;
        case R.id.menu_gallery_sharp:
            sProessor = new ImageSharper(mBitmapBackup);
            break;
        case R.id.menu_gallery_blur:
            sProessor = new ImageBlurer(mBitmapBackup);
            break;
        case R.id.menu_gallery_shadow:
            sProessor = new ImageReflection(mBitmapBackup);
            break;
        case R.id.menu_gallery_sketch:
            sProessor = new ImageSketcher(mBitmapBackup);
            break;
        case R.id.menu_gallery_reverse:
            sProessor = new ImageReverser(mBitmapBackup);
            break;
        default:
            break;
        }
        sProessor.setHandler(mHandler);
        Thread sThread = new Thread(sProessor);
        sThread.start();
        isProcessing = true;
        setProgressBarIndeterminateVisibility(true);
        tips.setText("Image is processing, please wait.");
        return true;
    }
    
    
    public boolean onKeyUp(int keyCode, KeyEvent event){
        if(keyCode == KeyEvent.KEYCODE_0){
            switcher.startAnimation(new TVOffAnimation());
        }else if(keyCode == KeyEvent.KEYCODE_1){
            saveImage();
        }else if(keyCode == KeyEvent.KEYCODE_2){
            switcher.startAnimation(mAnimation);
        }
        return super.onKeyUp(keyCode, event);
    }
    
    private void saveImage(){
        tips.setText("Image is saveing.");
        Thread sThread = new Thread(new ImageProcessor(mBitmap) {
            
            @Override
            protected Bitmap process() {
                // XXX Auto-generated method stub
                save();
                return mBitmap;
            }
        });
        sThread.start();
    }  
    
    private class MyImageAdapter extends BaseAdapter{
        private Context context;
        
        // 用来设置ImageView的风格
        int mGalleryItemBackground;
        
        public MyImageAdapter(Context context) {
            // TODO Auto-generated constructor stub
            this.context = context;
        }

        // 返回所有图片的个数
    //  @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return images.size();//mImageIds.length;
        }

        // 返回图片在资源的位置
    //  @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return images.get(position);//new Integer(position);
        }

    //  // 返回图片在资源的位置
    //  @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        // 此方法是最主要的，他设置好的ImageView对象返回给Gallery
    //  @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ImageView imageView = new ImageView(context);
            // 通过索引获得图片并设置给ImageView
 //           imageView.setImageResource(mImageIds[position]);
            imageView.setImageBitmap(images.get(position));
            // 设置ImageView的伸缩规格，用了自带的属性值
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            // 设置布局参数
            imageView.setLayoutParams(new Gallery.LayoutParams(160, 120));
            // 设置风格，此风格的配置是在xml中
            imageView.setBackgroundResource(mGalleryItemBackground);
            return imageView;
            
//            ImageView i = new ImageView(myContext);
//            // 绗�澶勬敼杩涳紝閫氳繃鍙栦綑鏉ュ惊鐜彇寰梞ThumbIds鏁扮粍涓殑鍥惧儚璧勬簮ID
//            i.setImageResource(mThumbIds[position%mThumbIds.length]);
////          i.setImageResource(mThumbIds[position]);
//            i.setScaleType(ImageView.ScaleType.FIT_XY);
//            i.setLayoutParams(new Gallery.LayoutParams(
//                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//            return i;
        }

//        public int getGalleryItemBackground() {
//            return mGalleryItemBackground;
//        }

        public void setGalleryItemBackground(int mGalleryItemBackground) {
            this.mGalleryItemBackground = mGalleryItemBackground;
        }
        
    }

    public void onAnimationEnd(Animation animation) {
        // XXX Auto-generated method stub
        
    }

    public void onAnimationRepeat(Animation animation) {
        // XXX Auto-generated method stub
        
    }

    public void onAnimationStart(Animation animation) {
        // XXX Auto-generated method stub
        
    }

    public View makeView() {
        // XXX Auto-generated method stub
        ImageView mImageView = new ImageView(this);   
        mImageView.setBackgroundColor(0xFF000000);   
        mImageView.setScaleType(ImageView.ScaleType.CENTER);//居中   
        mImageView.setLayoutParams(new ImageSwitcher.LayoutParams(//自适应图片大小   
        LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));   
        return mImageView;  
    }
}
